package org.sbi.satvik.model;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.sbi.satvik.beans.User;
import org.sbi.satvik.utility.HibernateUtil;

public class Login {
	public static String retrunString = "";
	
	public static String authenticate(User user){
		
		
		
		if (getUserByUserId(user) != null)
			retrunString = "success";
		else
			retrunString = "faild";
			
		
		
		
		return retrunString;
		
	}
	
	public static User getUserByUserId(User user) {
		 Session session = HibernateUtil.openSession();
		 Transaction tx = null;
		 User user1 = null;
		 try {
			 tx = session.getTransaction();
			 tx.begin();
			/*user=  (UserDetail)session.get(UserDetail.class, Integer.parseInt(userId));*/
			 
			 Query query = session.createQuery("from User where USER_NAME='"+user.getName()+"' and USER_PASSWORD="+user.getPassword());
	            user = (User)query.uniqueResult();
			//System.out.println("username is==="+user.getFirstName());
			 tx.commit();
		 } catch (Exception e) {
			 if (tx != null) {
				 tx.rollback();
			 }
			 e.printStackTrace();
		 } finally {
			 session.close();
		 }
		 return user;
	}
	
	/**
	 *  Register the user 
	 * @param user
	 * @return String Massage
	 */
	public static String loginReg(User user){
		retrunString = "";
		
		/**
		 * checking user is exist 
		 */
		if(isUserExists(user)){
			System.out.println("here in isUserExists");
			return retrunString = "UserExsit";
		}
		
		/**
         * hibernate operation for saving data
         */
		Session session = HibernateUtil.openSession();
		
		Transaction tx = null;	
		 try {
			 tx = session.getTransaction();
			 tx.begin();
			 session.saveOrUpdate(user);		
			 tx.commit();
		 } catch (Exception e) {
			 if (tx != null) {
				 tx.rollback();
			 }
			 retrunString = "Error";
			 e.printStackTrace();
		 } finally {
			 session.close();
		 }	
		/**
		 * End data Save
		 */
		
		 retrunString = "savedSuccess";
		
		
		return retrunString;
		
	}
	public static boolean isUserExists(User user){
		
		System.out.println("here in isUserExists...................");
		
		 Session session = HibernateUtil.openSession();
		 boolean result = false;
		 Transaction tx = null;
		 try{
			 tx = session.getTransaction();
			 tx.begin();
			 Query query = session.createQuery("from User where USER_NAME='"+user.getName()+"'");
			 System.out.println(query);
			 
			 User u = (User)query.uniqueResult();
			 tx.commit();
			 if(u!=null) result = true;
		 }catch(Exception ex){
			 if(tx!=null){
				 tx.rollback();
			 }
			 ex.printStackTrace();
		 }finally{
			 session.close();
		 }
		 return result;
	}
}
